package top.kpromise.fastdev.goods.service;

import org.springframework.stereotype.Service;
import top.kpromise.fastdev.goods.mapper.generated.SkuMapper;
import top.kpromise.fastdev.goods.mapper.goods.ISkuMapper;
import top.kpromise.fastdev.goods.mapper.goods.ISpuMapper;
import top.kpromise.fastdev.goods.model.request.CreateSkuModel;
import top.kpromise.fastdev.goods.model.sql.Sku;
import top.kpromise.fastdev.goods.model.sql.Spu;
import top.kpromise.fastdev.goods.response.Result;
import top.kpromise.fastdev.goods.utils.DateUtils;
import top.kpromise.fastdev.goods.utils.SnowflakeIdWorker;
import top.kpromise.fastdev.goods.utils.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Service
public class SkuService {

    private final SkuMapper skuMapper;
    private final ISkuMapper iSkuMapper;
    private final ISpuMapper iSpuMapper;

    public SkuService(SkuMapper skuMapper, ISpuMapper iSpuMapper, ISkuMapper iSkuMapper) {
        this.skuMapper = skuMapper;
        this.iSpuMapper = iSpuMapper;
        this.iSkuMapper = iSkuMapper;
    }

    public Map<String, Object> create(CreateSkuModel createSkuModel) {
        String skuId = SnowflakeIdWorker.generateId();

        ArrayList<Spu> requestList = createSkuModel.getSpuList();
        if (requestList == null || requestList.isEmpty()) {
            return Result.error("spu 信息不能为空");
        }
        ArrayList<Spu> spuList = new ArrayList<>();
        for (Spu tmp : requestList) {
            if (!StringUtils.isEmpty(tmp.getSpuName()) && !StringUtils.isEmpty(tmp.getSpuValue())) {
                tmp.setSkuId(skuId);
                tmp.setId(SnowflakeIdWorker.generateId());
                spuList.add(tmp);
            }
        }
        if (spuList.isEmpty()) {
            return Result.error("spu 信息不能为空");
        }
        Sku sku = new Sku();
        sku.setId(skuId);
        sku.setGoodsId("yByg18WkBjg6");
        sku.setSaleCount(0);
        sku.setEnabled(0);
        sku.setOnSale(0);
        sku.setCreatedAt(DateUtils.currentDate());
        sku.setUpdateAt(sku.getCreatedAt());
        sku.setPrice(createSkuModel.getPrice());
        sku.setStock(createSkuModel.getStock());
        skuMapper.insert(sku);
        iSpuMapper.insertForeach(spuList);
        return Result.data("新增成功");
    }

    public Map<String, Object> search(String title, int pageNo, int pageSize) {
        Map<String, Object> map = new HashMap<>();
        map.put("count", iSkuMapper.searchCount(title, (pageNo - 1) * pageSize, pageSize));
        map.put("list", iSkuMapper.search(title, (pageNo - 1) * pageSize, pageSize));
        return map;
    }
}